package _case

import (
	"context"
	"fmt"
	"time"
)

func ContextCase() {
	// 创建一个空的上下文
	ctx := context.Background()
	//给上下文赋值
	ctx = context.WithValue(ctx, "name", "John Doe")
	//设置超时时间
	ctx, cancel := context.WithTimeout(ctx, time.Second*2)
	defer cancel()

	data := [][]int{{1, 2}, {3, 4}}
	ch := make(chan []int)
	go calculate(ctx, ch)
	for _, d := range data {
		ch <- d
	}
	time.Sleep(time.Second * 10)

	//通道通知退出协程
	//done := make(chan struct{})
	//go f1(done)
	//go f1(done)
	//time.Sleep(3 * time.Second)
	//close(done)
}

func calculate(ctx context.Context, ch <-chan []int) {
	for {
		select {
		case data := <-ch:
			ctx := context.WithValue(ctx, "name", "calculate")
			ch1 := make(chan []int)
			go sumContext(ctx, ch1)
			ch1 <- data

			ch2 := make(chan []int)
			go multiContext(ctx, ch2)
			ch2 <- data

			fmt.Println(data)
		case <-ctx.Done():
			desc := ctx.Value("name").(string)
			fmt.Printf("calculate 协程退出，context desc:%s，错误信息：%s\n", desc, ctx.Err())
			return
		}
	}
}

func sumContext(ctx context.Context, ch <-chan []int) {
	for {
		select {
		case data := <-ch:
			a, b := data[0], data[1]
			res := sum(a, b)
			fmt.Printf("%d + %d = %d\n", a, b, res)
		case <-ctx.Done():
			desc := ctx.Value("name").(string)
			fmt.Printf("sumContext 协程退出，context desc:%s，错误信息：%s\n", desc, ctx.Err())
			return
		}
	}
}

func multiContext(ctx context.Context, ch <-chan []int) {
	for {
		select {
		case data := <-ch:
			a, b := data[0], data[1]
			res := multi(a, b)
			fmt.Printf("%d * %d = %d\n", a, b, res)
		case <-ctx.Done():
			desc := ctx.Value("name").(string)
			fmt.Printf("multiContext 协程退出，context desc:%s，错误信息：%s\n", desc, ctx.Err())
			return
		}
	}
}

func sum(a, b int) int {
	return a + b
}

func multi(a, b int) int {
	return a * b
}

func f1(done <-chan struct{}) {
	for {
		select {
		case <-done:
			fmt.Println("协程退出")
			return

		}
	}
}
